package com.jx.lcs.knowledge.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jx.lcs.knowledge.entity.KnowledgeInfo;
import com.jx.lcs.knowledge.service.KnowledgeInfoService;
import com.jx.lcs.util.common.CharUtil;
import com.jx.lcs.util.common.GetProp;
import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.persistence.PropertyFilter;
import com.tianyu.jty.common.utils.DateUtils;
import com.tianyu.jty.common.web.BaseController;

/**
 * @author 陈新雷 2015年7月2日下午4:49:05
 *
 */
@Controller
@RequestMapping("knowledge")
public class KnowledgeInfoController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(KnowledgeInfoController.class);

	@Autowired
	private KnowledgeInfoService ks;

	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "knowledge/knowledgeList";
	}

	/**
	 * 得到全部数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "klg/json", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getAll(HttpServletRequest request) {
		setOrderBy("publishTime");
		setOrder("DESC");
		Page<KnowledgeInfo> page = getPage(request);
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(request);
		page = ks.search(page, filters);
		return getEasyUIData(page);
	}

	/**
	 * 添加新闻跳转
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("kgi", new KnowledgeInfo());
		model.addAttribute("action", "create");
		return "knowledge/knowledgeForm";
	}

	/**
	 * 修改新闻跳转
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") String id, Model model) {
		model.addAttribute("kgi", ks.get(id));
		model.addAttribute("action", "update");
		return "knowledge/knowledgeForm";
	}

	/**
	 * 编辑新闻跳转
	 */
	@RequestMapping(value = "editor/{id}", method = RequestMethod.GET)
	public String editorForm(@PathVariable("id") String id, Model model) {
		 model.addAttribute("kgi", ks.get(id));
		model.addAttribute("action", "editored");
		return "knowledge/knowledgeEditor";
	}
	/**
	 * 图片跳转
	 */
	@RequestMapping(value = "upload/{id}", method = RequestMethod.GET)
	public String uploadForm(@PathVariable("id") String id, Model model) {
		 model.addAttribute("id", id);
		model.addAttribute("action", "upload");
		return "knowledge/knowledgeUpload";
	}

	/**
	 * 生成html文件
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "editored", method = RequestMethod.POST)
	@ResponseBody
	public String editored(@Valid @ModelAttribute("kgi") KnowledgeInfo kgi, Model model) {
		try{
			KnowledgeInfo knowledge = ks.get(kgi.getId());
			if(knowledge != null) {
				String content = kgi.getContent();
				Long tm = System.currentTimeMillis();
				String nm = tm+".html";
				String title = knowledge.getTitle();
				ks.createhtml(title, content,nm);
				knowledge.setUrl(GetProp.getConfig("NEWS_HTML_SERVER_URL")+nm);
				knowledge.setContent(content);
				ks.save(knowledge);
				
				return "success";
			} else {
				return "该文章不存在！";
			}
		} catch(Exception e) {
			return "编辑文章出现异常！！";
		}
	}

	/**
	 * 增加新闻
	 * 
	 * @param KnowledgeInfo
	 * @param model
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(@Valid KnowledgeInfo kgi, Model model) {
		if ("".equals(kgi.getId()))
			kgi.setId(null);
		
		String title = kgi.getTitle().trim();
		title = CharUtil.charConvert(title);
		
		kgi.setTitle(title);
		kgi.setPublishStatus("0");
		ks.save(kgi);
		return "success";
	}

	/**
	 * 修改新闻
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute("kgi") KnowledgeInfo kgi,
			Model model) {
		KnowledgeInfo tem=ks.get(kgi.getId());
		
		String title = kgi.getTitle().trim();
		title = CharUtil.charConvert(title);
		
		tem.setTitle(title);
		tem.setConttype(tem.getConttype());
		tem.setHotlevel(kgi.getHotlevel());
		tem.setSource(kgi.getSource());
		ks.update(tem);
		
		return "success";
	}

	/**
	 * 根据id删除数据
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id) {
		ks.delete(id);
		return "success";
	}

	/**
	 * 新闻内部图片上传
	 * 
	 * @param ctx
	 * @throws IOException
	 */
	@RequestMapping(value = "upload_json", method = RequestMethod.POST)
	public void fileUpload(@RequestParam MultipartFile upload,
			HttpServletRequest request, HttpServletResponse response) {
		String path =GetProp.getConfig("NEWS_CONT_IMG_UPLOAD_PATH");
		PrintWriter out = null;
		Long tm=System.currentTimeMillis();
		String fileName = upload.getOriginalFilename();
		fileName=""+tm+fileName.substring(fileName.lastIndexOf("."));
		// CKEditor提交的很重要的一个参数
		String callback = request.getParameter("CKEditorFuncNum");
		if (null != fileName && !"".equals(fileName)) {
			// 保存
			try {
				out = response.getWriter();
				File targetFile = new File(path, fileName);
				if (targetFile.exists()) {
					targetFile.delete();
				}
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				upload.transferTo(targetFile);
			} catch (Exception e) {
				logger.info("上传头像异常:", e);
				e.printStackTrace();
			}
		}
		
		try {
			//线程等待1秒，图片文件同步至文件服务器后访问
			Thread.sleep(1500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
		out.println("<script type=\"text/javascript\">");
		out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
				+ ",'" + GetProp.getConfig("NEWS_CONT_IMG_SERVER_URL")+fileName + "','')");
		out.println("</script>");
	}
	/**
	 * 图片上传
	 * 
	 * @param ctx
	 * @throws IOException
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam MultipartFile img,
			HttpServletRequest request, HttpServletResponse response) {
		String path =GetProp.getConfig("NEWS_HEAD_IMG_UPLOAD_PATH");
		Long tm=System.currentTimeMillis();
		String fileName = img.getOriginalFilename();
		String id=request.getParameter("id");
		fileName=""+tm+fileName.substring(fileName.lastIndexOf("."));
		if (null != fileName && !"".equals(fileName)) {
			// 保存
			try {
				File targetFile = new File(path, fileName);
				if (targetFile.exists()) {
					targetFile.delete();
				}
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				img.transferTo(targetFile);
				KnowledgeInfo kgi=ks.get(id);
				kgi.setImgurl(GetProp.getConfig("NEWS_HEAD_IMG_SERVER_URL")+fileName);
				ks.save(kgi);
			} catch (Exception e) {
				logger.info("上传头像异常:", e);
				e.printStackTrace();
			}
		}
		return "success";
	}
	/**
	 * 发布文章
	 * 
	 * @return
	 */
	@RequestMapping(value = "publish/{id}")
	@ResponseBody
	public String update(@PathVariable("id") String id) {
		try {
			KnowledgeInfo info = ks.get(id);
			if (info != null) {
				info.setPublishStatus("1");
				info.setPublishTime(DateUtils.getSysDate());

				ks.update(info);
			}
		} catch (Exception e) {
			logger.error("--发布文章出现异常！！", e);
		}

		return "success";
	}
}
